package org.csu.mypetstore.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.csu.mypetstore.api.common.CommonResponce;
import org.csu.mypetstore.api.entity.Account;
import org.csu.mypetstore.api.entity.Cart;
import org.csu.mypetstore.api.entity.Item;
import org.csu.mypetstore.api.entity.Product;
import org.csu.mypetstore.api.persistence.*;
import org.csu.mypetstore.api.service.CartService;
import org.csu.mypetstore.api.vo.CartItemVO;
import org.csu.mypetstore.api.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired ItemMapper itemMapper;
    @Autowired OrderMapper orderMapper;
    @Autowired CartMapper cartMapper;
    @Autowired ProductMapper productMapper;
    @Autowired AccountMapper accountMapper;
    @Override
    public CommonResponce<List<Cart>> getCart(String username) {
        if (username.isEmpty()||username==null){
            return CommonResponce.createForError(1," 您还没有登录，请登录");
        }
        QueryWrapper<Cart>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userid",username);

        int num=cartMapper.selectList(queryWrapper).size();
        if (num==0){
            return CommonResponce.createForError("购物车为空，请购买商品");
        }
        List<Cart> cartList=cartMapper.selectList(queryWrapper);
        return CommonResponce.createForSuccess("查询成功",cartList);
    }

    @Override
    public CommonResponce<Cart> addItem(String username, String itemId) {
        if (username.isEmpty()||username==null){
            return CommonResponce.createForError(1," 宁还没有登录，请登录");
        }
        //检验商品是否存在
        Item item= itemMapper.selectById(itemId);

        //查询数据库表中是否有该用户下的item
        QueryWrapper<Cart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userid",username)
                .eq("itemid",itemId);
        List<Cart> cartList=cartMapper.selectList(queryWrapper);
        if (cartList.isEmpty()){
            //添加到数据库
            try{
                Cart cart=new Cart();
                InsertNewOrderintoOrder(username,itemId,cart);
                cartMapper.insert(cart);//此处有问题
            }catch (Exception e){
                e.printStackTrace();
            }
            return CommonResponce.createForSuccessMessage(0,"添加成功");
        }
        else {
            //购物车内已经存在该item
            Cart cart=cartMapper.selectOne(queryWrapper);
            int quantity= cart.getQuantity()+1;
            BigDecimal itemtotal=cart.getUnitprice().multiply(BigDecimal.valueOf(quantity));
            cart.setQuantity(quantity);
            cart.setItemtotal(itemtotal);

            UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("userid", username)
                    .eq("itemid", itemId)
                    .set("quantity", cart.getQuantity())
                    .set("itemtotal", cart.getItemtotal());
            int updatedRows = cartMapper.update(null, updateWrapper);
            if (updatedRows == 0) {
                return CommonResponce.createForError(1, "更新购物车失败");
            }else return CommonResponce.createForSuccessMessage(0,"添加成功");
        }
    }

    //删除某一条cart
    @Override
    public CommonResponce<CartVo> removeItem(String username, String itemId) {
        QueryWrapper<Cart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userid",username)
                .eq("itemid",itemId);
        cartMapper.delete(queryWrapper);
        return  CommonResponce.createForSuccessMessage("删除成功");
    }

    //根据当前的数量修改item信息
    @Override
    public CommonResponce<CartItemVO> updateQuantity(String username, String itemId, int quantity) {
        QueryWrapper<Cart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userid",username)
                .eq("itemid",itemId);
        if (quantity==0){
            //删除item
            cartMapper.delete(queryWrapper);
        }else {
            // 查询现有条目
            Cart cart = cartMapper.selectOne(queryWrapper);
            if (cart == null) {
                return CommonResponce.createForError("购物车条目不存在");
            }
            //构造更新条件
            cart.setQuantity(quantity);
            cart.setItemtotal(cart.getUnitprice().multiply(BigDecimal.valueOf(cart.getQuantity())));
            UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("userid", username)
                    .eq("itemid", itemId)
                    .set("quantity", cart.getQuantity())
                    .set("itemtotal", cart.getItemtotal());

            // 执行更新
            int updatedRows = cartMapper.update(null, updateWrapper);
            if (updatedRows == 0) {
                return CommonResponce.createForError("更新购物车失败");
            }
            return CommonResponce.createForSuccessMessage("删除成功");
        }
        return CommonResponce.createForError(1,"服务器异常");
    }

    //将一条item信息添加到cart表
    private  void InsertNewOrderintoOrder(String username,String itemId,Cart cart){
        Item item=itemMapper.selectById(itemId);
        Account account=accountMapper.selectById(username);
        cart.setUserid(username);
        cart.setItemid(itemId);
        cart.setProductid(item.getProductId());
        cart.setQuantity(1);
        cart.setUnitprice(item.getListPrice());
        cart.setSupplier(1);
        cart.setStatus(account.getStatus());
        cart.setAttr1(item.getAttribute1());
        cart.setItemtotal(cart.getUnitprice().multiply(BigDecimal.valueOf(cart.getQuantity())));//计算总价
    }
}
